<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { MenuStores } from '@/stores/MenuStores'

const menuStore = MenuStores()

const emit = defineEmits(['update:visible', 'success'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  menuData: {
    type: Object,
    default: () => ({})
  }
})

const formRef = ref()
const loading = ref(false)

const form = reactive({
  id: null,
  name: '',
  path: '',
  component: '',
  icon: '',
  sort: 0,
  isDelete: 0,
  parentId: null,
  aclId: null
})

const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ]
}

watch(
    () => props.menuData,
    (newMenuData) => {
      if (newMenuData && Object.keys(newMenuData).length > 0) {
        Object.assign(form, {
          id: newMenuData.id || null,
          name: newMenuData.name || '',
          path: newMenuData.path || '',
          icon: newMenuData.icon || '',
          sort: newMenuData.sort || 0,
          isDelete: newMenuData.isDelete || 0,
          parentId: newMenuData.parentId || null,
          aclId: newMenuData.aclId || null
        })
      } else {
        Object.assign(form, {
          id: null,
          name: '',
          path: '',
          icon: '',
          sort: 0,
          isDelete: 0,
          parentId: null,
          aclId: null
        })
      }
    },
    { immediate: true, deep: true }
)

const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

const handleSubmit = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    const submitData = {
      ...form,
      sort: Number(form.sort),
      isDelete: Number(form.isDelete),
      parentId: form.parentId ? Number(form.parentId) : null,
      aclId: form.aclId ? Number(form.aclId) : null
    }

    if (!submitData.id) {
      await menuStore.create(submitData)
      ElMessage.success('菜单创建成功')
    } else {
      await menuStore.update(submitData)
      ElMessage.success('菜单更新成功')
    }

    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'validate') {
      console.error('保存菜单失败:', error)
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
      :model-value="visible"
      :title="form.id ? '编辑菜单' : '新增菜单'"
      width="500px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
    >
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入菜单名称" clearable />
      </el-form-item>

      <el-form-item label="菜单路径" prop="path">
        <el-input v-model="form.path" placeholder="请输入菜单路径" clearable />
      </el-form-item>


      <el-form-item label="图标" prop="icon">
        <el-input v-model="form.icon" placeholder="请输入图标名称" clearable />
      </el-form-item>

      <el-form-item label="父菜单ID">
        <el-input-number v-model="form.parentId" :min="0" controls-position="right" style="width: 100%" />
      </el-form-item>

      <el-form-item label="权限ID">
        <el-input-number v-model="form.aclId" :min="0" controls-position="right" style="width: 100%" />
      </el-form-item>

      <el-form-item label="排序">
        <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
      </el-form-item>

      <el-form-item label="状态" v-if="form.id">
        <el-tag :type="form.isDelete === 0 ? 'success' : 'danger'">
          {{ form.isDelete === 0 ? '正常' : '已删除' }}
        </el-tag>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
            :disabled="form.isDelete === 1"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>